<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/3
 * Time: 15:13
 */
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Validate;
use think\Db;
use think\Session;

class Wxapi extends Controller{
    private $config_session;
    //初始化
    public function _initialize()
    {
        $this->config_session = array(
            'prefix'            => 'api',       // session 名称前缀
            'expire'            => 7200,        // session 过期时间
            'use_trans_sid'     =>  0,          //跨页传递
            'use_only_cookies'  =>  0,          //是否只开启基于cookies的session的会话方式
        );
    }
    public function login(){
        $request = Request::instance();
        //是否get请求
        if($request->isPost()){
            $param = $request->param();
            $rules = [
                'code' => 'require'
            ];
            $Fields = ['code'];
            $validate = new Validate($rules);
            if (!$validate->check($param)) {
                exit(json_encode(array('code'=>2,'msg'=>$validate->getError()),JSON_UNESCAPED_UNICODE));
            }else{
                $data = $request->only($Fields);
                //获取appid和appsecret
                $wxconfig = Db::name('wxconfig')->find();
                $appId = $wxconfig['appid'];
                $AppSecret = $wxconfig['appsecret'];
                $authcode2Sessionhost = $wxconfig['authcode2Sessionhost'];
                $js_code = $data['code'];
                $url = $authcode2Sessionhost.'?appid='.$appId.'&secret='.$AppSecret.'&js_code='.$js_code.'&grant_type=authorization_code';
                $res = file_get_contents($url);
                $res = json_decode($res,true);

                //将openid和session_key存到session里
                $session = new Session($this->config_session);
                $session->prefix();
                $session->set('openid',$res['openid'],$this->config_session['prefix']);
                $session->set('session_key',$res['session_key'],$this->config_session['prefix']);

                //查询库里是否已经存在
                $user = Db::name('user')->where(array('openid'=>$res['openid']))->find();
                if(empty($user)){
                    //信息入库
                    $insertData = array(
                        'openid' => $res['openid'],
                        'session_key' => $res['session_key'],
                        'first_visit_time' => time(),
                        'last_visit_time' => time(),
                        'visit_count' => 1,
                    );
                    Db::name('user')->insert($insertData);
                }else{
                    $count = $user['visit_count'] + 1;
                    $updateData = array(
                        'session_key' => $res['session_key'],
                        'last_visit_time' => time(),
                        'visit_count' => $count,
                    );
                    Db::name('user')->where('id',$user['id'])->update($updateData);
                }
                if($res != false){
                    echo json_encode(array('code'=>0,'msg'=>'成功'),JSON_UNESCAPED_UNICODE);
                }else{
                    exit(json_encode(array('code'=>1,'msg'=>'失败'),JSON_UNESCAPED_UNICODE));
                }
            }
        }else{
            echo json_encode(array('code'=>12,'msg'=>'非post请求'),JSON_UNESCAPED_UNICODE);
        }
    }
    public function checkSession(){
        $request = Request::instance();
        //是否get请求
        if($request->isPost()){
            if ($_COOKIE['PHPSESSID']) {
                session_id($_COOKIE['PHPSESSID']);
                if(!Session::has('openid',$this->config_session['prefix']) || !Session::has('session_key',$this->config_session['prefix'])){
                    //'session过期了';
                    exit(json_encode(array('code'=>6,'msg'=>'SESSION过期了','data'=>[]),JSON_UNESCAPED_UNICODE));
                }else{
                    $openid = Session::get('openid',$this->config_session['prefix']);
                    echo json_encode(array('code'=>0,'msg'=>'SESSION未过期','data'=>['openid'=>$openid]),JSON_UNESCAPED_UNICODE);
                }
            }else{
               //sessionid不存在，请重新登录
                echo json_encode(array('code'=>7,'msg'=>'PHPSESSID不存在','data'=>[]),JSON_UNESCAPED_UNICODE);
            }
        }else{
            echo json_encode(array('code'=>12,'msg'=>'非post请求','data'=>[]),JSON_UNESCAPED_UNICODE);
        }
    }
    public function saveUserInfo(){
        $request = Request::instance();
        //是否get请求
        if($request->isPost()){
            $param = $request->param();
            $rules = [
                'userInfo' => 'require'
            ];
            $Fields = ['userInfo'];
            $validate = new Validate($rules);
            if (!$validate->check($param)) {
                exit(json_encode(array('code'=>2,'msg'=>$validate->getError()),JSON_UNESCAPED_UNICODE));
            }else{
                $data = $request->only($Fields);
                $userInfo = $data['userInfo'];
                $this->check();
                $openid = Session::get('openid',$this->config_session['prefix']);
                $session_key = Session::get('session_key',$this->config_session['prefix']);
                //查询数据库是否存在，不存在插入，存在，更新
                $user = Db::name('user')->where(array('openid'=>$openid))->find();
                if(empty($user)){
                    Db::name('user')->insert(array(
                        'openid'=>$openid,
                        'session_key'=>$session_key,
                        'nickname'=>$userInfo['nickName'],
                        'gender'=>$userInfo['gender'],
                        'language'=>$userInfo['language'],
                        'city'=>$userInfo['city'],
                        'province'=>$userInfo['province'],
                        'country'=>$userInfo['country'],
                        'avatarUrl'=>$userInfo['avatarUrl'],
                    ));
                }else{
                    Db::name('user')->where(array('id'=>$user['id']))->update(array(
                        'nickname'=>$userInfo['nickName'],
                        'gender'=>$userInfo['gender'],
                        'language'=>$userInfo['language'],
                        'city'=>$userInfo['city'],
                        'province'=>$userInfo['province'],
                        'country'=>$userInfo['country'],
                        'avatarUrl'=>$userInfo['avatarUrl'],
                    ));
                }
                exit(json_encode(array('code'=>0,'msg'=>'成功'),JSON_UNESCAPED_UNICODE));
            }
        }else{
            exit(json_encode(array('code'=>12,'msg'=>'非post请求'),JSON_UNESCAPED_UNICODE));
        }
    }
    private function check(){
        if ($_COOKIE['PHPSESSID']) {
            session_id($_COOKIE['PHPSESSID']);
            if(!Session::has('openid',$this->config_session['prefix']) || !Session::has('session_key',$this->config_session['prefix'])){
                //'session过期了';
                exit(json_encode(array('code'=>6,'msg'=>'SESSION过期了','data'=>[]),JSON_UNESCAPED_UNICODE));
            }
        }else{
            //sessionid不存在，请重新登录
            exit(json_encode(array('code'=>7,'msg'=>'PHPSESSID不存在','data'=>[]),JSON_UNESCAPED_UNICODE));
        }
    }
    /**
     * 地址接口
     *
    */
    public function address(){
        $rules = [
            'name' => 'require',
            'gender' => 'require',
            'mobile' => 'require',
            'address' => 'require',
            'housenumber' => 'require',
            'label' => 'require',
            'isdefault' => 'require',
        ];
        $Fields = ['id','name','gender','mobile','address','housenumber','label','isdefault'];
        $request = Request::instance();
        if($request->isGet()){//获取列表
            $id = $request->param('id');
            echo dataList('address',$this->config_session['prefix'],$id);
        }elseif ($request->isPost()){//创建地址
            echo saveData('address',$this->config_session['prefix'],$rules,$Fields);
        }elseif ($request->isPut()){//修改地址
            echo saveData('address',$this->config_session['prefix'],$rules,$Fields);
        }elseif ($request->isDelete()){//删除地址
            $id = $request->param('id');
            echo deleteData('address',$this->config_session['prefix'],$id);
        }else{
            echo json_encode(array('code'=>405,'msg'=>'Method Not Allowed','data'=>[]),JSON_UNESCAPED_UNICODE);
        }
    }
    /**
     * 购物车接口
    */
    public function cart(){
        $rules = [
            'img_url' => 'require',
            'title' => 'require',
            'current_price' => 'require',
            'original_price' => 'require',
            'number' => 'require',
            'checked' => 'require',
        ];
        $Fields = ['id','img_url','title','current_price','original_price','number','checked'];
        $request = Request::instance();
        if($request->isGet()){//获取列表
            $id = $request->param('id');
            echo dataList('cart',$this->config_session['prefix'],$id);
        }elseif ($request->isPost()){//创建购物车
            echo saveData('cart',$this->config_session['prefix'],$rules,$Fields);
        }elseif ($request->isPut()){//修改购物车
            echo saveData('cart',$this->config_session['prefix'],$rules,$Fields);
        }elseif ($request->isDelete()){//删除购物车
            $id = $request->param('id');
            echo deleteData('cart',$this->config_session['prefix'],$id);
        }else{
            echo json_encode(array('code'=>405,'msg'=>'Method Not Allowed','data'=>[]),JSON_UNESCAPED_UNICODE);
        }
    }
}